<!-- 任务批阅 -->
<template>
	<a-modal
		fullscreen
		v-model:visible="visible"
		simple
		:footer="false"
		hide-title
		body-class="lsh-modal-body"
		modal-class="lsh-modal"
		:unmount-on-close="true"
		:esc-to-close="false"
	>
		<div class="lsh-box">
			<div class="lsh-left">
				<Mark
					ref="markRef"
					:info="{
						avatar: userData.avatarUrl,
						totalScore: userData.questionScore,
						score: userData.myScore,
						label: userData.markItem?.label,
						username: userData.uname,
						userId: userData.uid,
						topicNumStr: info.numStr
					}"
					:config="{
						setLable: false
					}"
					v-if="showMark"
				/>
				<BigScreen ref="bigScreenRef" v-else>
					<QuestionShow
						:ques-item="questionInfo"
						:id="info.questionId"
						:parent-id="info.parentQuestionId"
					>
						<template #answer-detail="{ id }" v-if="showAnswer">
							<answer-show
								:answerItem="getAnswerById(id)"
								v-if="!loading"
							></answer-show>
						</template>
					</QuestionShow>
				</BigScreen>
			</div>
			<div class="lsh-right">
				<div
					:class="{
						'lsh-right-top': true,
						expand
					}"
				>
					<Transition>
						<div class="lsh-info-left">
							<AnswerDetail
								v-show="expand"
								:info="{
									...info,
									color: detailColor
								}"
							/>
							<Card title="学生名单" v-show="expand" class="lsh-student-list">
								<StudentList
									:info="info"
									@select="(item) => hanChangeUserId(item.id)"
								/>
							</Card>
						</div>
					</Transition>
					<div class="lsh-info-right">
						<NumberList
							:list="questionNumberList"
							:active-id="info.questionId"
							@change="hanChangeQuestionId"
						/>
					</div>
				</div>
				<div
					:class="{
						'lsh-btn-box': true,
						expand
					}"
				>
					<div class="lsh-btn-item" @click="expand = !expand">
						<svg-icon class="lsh-icon lsh-to-right" name="to-right" />
						<ExpandTransition :expand="expand" direction="width">
							<span>收起侧边栏</span>
						</ExpandTransition>
					</div>
					<div
						class="lsh-btn-item"
						@click="hanChangeUserId('')"
						v-show="info.userId !== ''"
					>
						<svg-icon class="lsh-icon" name="change" />
						<ExpandTransition :expand="expand" direction="width">
							<span>切换原题</span>
						</ExpandTransition>
					</div>
					<div class="lsh-btn-item" @click="hanClose">
						<svg-icon class="lsh-icon" name="exit" />
						<ExpandTransition :expand="expand" direction="width">
							<span>退出讲评</span>
						</ExpandTransition>
					</div>
				</div>
			</div>
		</div>
	</a-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import BigScreen from './compoents/big-screen/index.vue'
import Mark from './compoents/mark/index.vue'
import NumberList from './compoents/number-list/index.vue'
import StudentList from './compoents/student-list/index.vue'
import AnswerDetail from './compoents/answer-detail/index.vue'
import ExpandTransition from './compoents/transition/expand-transition.vue'
import { getTopicInfo } from '@/api/bigScreenTopic/index'
import Card from './compoents/card/index.vue'
import { QuestionNumberItem } from './type'
import { getColorByRate } from './config'
import QuestionShow from './compoents/question-show/index.vue'
import AnswerShow from './compoents/answer-show/index.vue'

const visible = defineModel('visible')
const expand = ref(true)
const info = ref<Record<string, any>>({
	userId: '',
	questionId: '',
	totalScore: 15,
	avgScore: 0,
	questTypeName: '',
	scoreRate: 0,
	classifyData: {},
	taskId: '',
	parentQuestionId: '',
	numStr: ''
})

const markRef = ref<InstanceType<typeof Mark> | null>()
const bigScreenRef = ref<InstanceType<typeof BigScreen> | null>()
const userInfoMap = ref(new Map())
const questionDataMap = ref(new Map())
const questionNumberList = ref<QuestionNumberItem[]>([])
const cacheDataMap = new Map()
const loading = ref(false)
const hanClose = () => {
	//清除缓存数据
	cacheDataMap.clear()
	info.value.userId = ''

	visible.value = false
}
const initUserList = async (params: { taskId: string; quesId: string }) => {
	try {
		if (!(params.taskId && params.quesId)) return
		loading.value = true
		const res = await getTopicInfo(params)
		info.value.avgScore = res.data.avgScore
		info.value.totalScore = res.data.quesScore
		info.value.scoreRate = res.data.scoreRate
		info.value.questTypeName = res.data.quesTypeName
		info.value.classifyData = res.data.classifyData
		userInfoMap.value.clear()
		Object.entries(res.data.classifyData).forEach(([k, v]) => {
			v.forEach((item) => {
				userInfoMap.value.set(item.uid, {
					...item,
					status: k
				})
			})
		})
	} catch (error) {
	} finally {
		loading.value = false
	}
}
const questionInfo = computed(() => {
	const targetId = info.value.parentQuestionId || info.value.questionId
	const res = questionDataMap.value.get(targetId) ?? {}
	if (!res?.children?.length) return res
	let children = res.children.map((item, index) => {
		return {
			...item,
			index
		}
	})
	if (info.value.parentQuestionId) {
		children = children.filter(
			(item) => item.questionId === info.value.questionId
		)
	}
	return {
		...res,
		children
	}
})
const userData = computed(() => {
	return userInfoMap.value.get(info.value.userId) ?? {}
})
const showAnswer = computed(() => {
	return info.value.userId !== ''
})
const showMark = computed(() => {
	if (info.value.userId === '') return false
	//如果为人工批阅题,且是展示某小题时才显示批阅;
	if (questionInfo.value?.children?.length > 1) return false
	const notAuto =
		['14', '15'].includes(questionInfo.value?.quesStruct) ||
		['14', '15'].includes(questionInfo.value?.children?.[0]?.quesStruct)
	return notAuto
})
const getCacheKey = () => {
	if (showMark.value) return info.value.questionId
	return `${info.value.questionId}-${info.value.userId}`
}
const setCacheData = () => {
	if (showMark.value)
		return cacheDataMap.set(getCacheKey(), markRef.value?.getData()?.dataList)
	cacheDataMap.set(getCacheKey(), bigScreenRef.value?.getData())
}
const initCanvas = async () => {
	await nextTick()
	if (showMark.value) {
		const data = userInfoMap.value.get(info.value.userId) ?? {}
		const dataList =
			cacheDataMap.get(getCacheKey()) ?? data.markItem?.[0]?.markInfo ?? []
		markRef.value?.setData({
			imgList: data.answerItem?.[0]?.value ?? [],
			dataList: dataList,
			label: data.markItem?.[0]?.markTopicId?.[0] ?? ''
		})
	} else {
		bigScreenRef.value?.setData(cacheDataMap.get(getCacheKey()) ?? '')
	}
}
const hanChangeQuestionId = async (data: Partial<QuestionNumberItem>) => {
	if (info.value.questionId !== '') {
		setCacheData()
	}
	info.value.questionId = data.questionId
	info.value.parentQuestionId = data.parentQuestionId
	info.value.numStr = data.num
	await initUserList({
		taskId: info.value.taskId,
		quesId: info.value.questionId
	})
	initCanvas()
}
const hanChangeUserId = (id: string) => {
	setCacheData()
	info.value.userId = id
	initCanvas()
}
const getAnswerById = (id: string) => {
	const markItem = userData.value?.markItem?.find((i) => i.questionId === id)
	const answerItem = userData.value?.answerItem?.find(
		(i) => i.questionId === id
	)
	console.log(markItem, answerItem)
	return {
		markItem,
		answerItem,
		questionInfoData: questionInfo.value
	}
}
const detailColor = computed(() => {
	if (info.value.questionId === '') return '#ff4c26'
	return questionNumberList.value.find((item) => {
		return item.questionId === info.value.questionId
	})?.color
})
defineExpose({
	open: (params: { taskId: string; data: any }) => {
		info.value.taskId = params.taskId
		const quesData = params.data
		questionDataMap.value.clear()
		const numberList: QuestionNumberItem[] = []
		quesData.questionInfoVos.forEach((item, index) => {
			questionDataMap.value.set(
				item.questionInfoData.questionId,
				item.questionInfoData
			)
			const scoreData = quesData.questionNumAndRates[index] || {
				markRate: 0
			}
			const parentQuestionId =
				item.questionAnswerInfo.parentQuestionId === item.questionId
					? null
					: item.questionAnswerInfo.parentQuestionId;
			numberList.push({
				num: item.questionNum,
				questionId: item.questionId,
				parentQuestionId: parentQuestionId,
				scoreRate: item.scoreRate,
				markRate: scoreData.markRate,
				color: getColorByRate(item.scoreRate, scoreData.markRate)
			})
		})
		questionNumberList.value = numberList
		visible.value = true
		const firstData = questionNumberList.value[0] || {}
		console.log(quesData)
		hanChangeQuestionId({
			questionId: firstData.questionId,
			parentQuestionId: firstData?.parentQuestionId ?? null
		})
	}
})
</script>
<style scoped lang="less">
@boxStyle: {
	border-radius: 16px;
	background: #fff;
	/* 卡片投影 */
	box-shadow: 0px 0px 8px 0px rgba(0, 101, 255, 0.06);
};
@gap: 6px;
.v-enter-active,
.v-leave-active {
	transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
	opacity: 0;
}
.lsh-box {
	width: 100%;
	height: 100%;
	display: flex;
	gap: 6px;
	background: #edf1f7;
	padding: 6px;
	.lsh-left {
		flex: 1;
		height: 100%;
		transform: translateZ(0); /* 强制启用硬件加速 */
		@boxStyle();
		overflow: hidden;
	}
	.lsh-right {
		width: fit-content;
		display: flex;
		flex-direction: column;
		gap: @gap;
		overflow: hidden;
		max-width: 450px;
		.lsh-right-top {
			display: flex;
			flex: 1;
			// gap: @gap;
			overflow: hidden;
			&.expand {
				gap: @gap;
			}
			.lsh-info-left {
				flex: 1;
				height: 100%;
				display: flex;
				flex-direction: column;
				gap: @gap;
				// @boxStyle();
				.lsh-student-list {
					flex: 1;
					overflow: hidden;
					:deep {
						.lsh-card-bottom {
							.lsh-bottom-content {
								padding: 0;
								padding-bottom: 13px;
							}
						}
					}
				}
			}
			.lsh-info-right {
				width: 104px;
				height: 100%;
				@boxStyle();
				margin-left: auto;
				overflow: hidden;
			}
		}

		.lsh-btn-box {
			flex-shrink: 0;
			@boxStyle();
			width: 104px;
			padding: 4px;
			height: fit-content;
			overflow: hidden;
			display: flex;
			justify-content: space-between;
			transition: width 0.2s cubic-bezier(0.34, 0.69, 0.1, 1);
			// gap: 12px;
			gap: 1px;
			will-change: width; // 提示浏览器这些属性将发生变化
			margin-left: auto;
			.lsh-btn-item {
				color: black;
				height: 44px;
				font-size: 16px;
				cursor: pointer;
				border-radius: 12px;
				padding: 12px 0;
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 4px;
				font-size: 14px;
				font-weight: 400;
				line-height: 1;
				&:hover {
					background: #edf1f7;
					color: #557ca7;
				}
				:deep(.lsh-icon) {
					font-size: 16px;
				}
				span {
					display: none;
					opacity: 0;
					transition: opacity 0.2s ease 0.2s;
					will-change: opacity; // 提示浏览器这些属性将发生变化
					white-space: nowrap; // 防止文本换行
				}
				&:nth-child(n + 2) {
					position: relative;
					&::after {
						content: '';
						position: absolute;
						top: 50%;
						left: -1px;
						transform: translateY(-50%);
						width: 1px;
						height: 8px;
						background-color: #e1e5eb;
					}
				}
			}

			&.expand {
				width: 450px;
				.lsh-btn-item {
					span {
						display: block;
						opacity: 1;
						width: fit-content;
					}
				}
			}
			&:not(.expand) {
				.lsh-to-right {
					transform: rotate(180deg);
					transform-origin: center;
				}
			}
		}
	}
	.lsh-resize-box {
		width: 20%;
		@boxStyle();
		:deep(.lsh-tool-btn) {
			color: red;
		}
	}
}
</style>
<style lang="less">
.lsh-modal {
	padding: 0;
	.lsh-modal-body {
		padding: 0 !important;
		height: 100%;
	}
}
</style>
